package cn.chinasyq.photoquan.photo.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.convenientbanner.CBViewHolderCreator;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.OnItemClickListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshHeaderGridView;

import java.util.ArrayList;
import java.util.List;

import cn.chinasyq.photoquan.AppConstant;
import cn.chinasyq.photoquan.GameIndexActivity;
import cn.chinasyq.photoquan.R;
import cn.chinasyq.photoquan.news.activity.ArticleInfoActivity;
import cn.chinasyq.photoquan.news.mode.NewsMode;
import cn.chinasyq.photoquan.photo.PhotoInfoActivity;
import cn.chinasyq.photoquan.photo.adapter.NetworkImageHolderView;
import cn.chinasyq.photoquan.photo.adapter.PhotoListAdapter;
import cn.chinasyq.photoquan.photo.bean.PhotoEntity;
import cn.chinasyq.photoquan.photo.bean.PhotoListEntity;
import cn.chinasyq.photoquan.photo.mode.PhotoMode;
import cn.chinasyq.photoquan.util.TimeUtil;
import cn.chinasyq.photoquan.view.LoadView;
import cn.master.util.utils.ScreenUtil;
import cn.master.util.utils.ToastUtil;
import cn.master.volley.models.response.handler.ResponseHandler;
import cn.master.volley.models.response.handler.ResponseHandler.OnFailedListener;
import cn.master.volley.models.response.handler.ResponseHandler.OnSucceedListener;
import cn.master.xlistview.view.XListView.RefreshTimeListener;

/**
 * Created by 一搏 on 2015/11/24.
 */
public class PhotoListFragment extends Fragment implements OnFailedListener, OnSucceedListener, PullToRefreshBase.OnRefreshListener2, RefreshTimeListener {
    private PullToRefreshHeaderGridView lv_content;
    private LoadView loadView;
    private final String TAG_REFRENSH = "refresh";
    private final String TAG_LOAD_MORE = "loadmore";
    private PhotoListAdapter adapter;
    private ConvenientBanner<PhotoEntity> v_n_top;
    private View topView;
    private ArrayList<PhotoEntity> posters;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_photography_exhibition, null);
        lv_content = (PullToRefreshHeaderGridView) view.findViewById(R.id.xlv_content);
        lv_content.getRefreshableView().setNumColumns(2);
        lv_content.setMode(PullToRefreshBase.Mode.BOTH);
        loadView = (LoadView) view.findViewById(R.id.loadview);
        loadView.setOnReLoadClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadView.setStatus(LoadView.Status.loading);
                refresh();
            }
        });
        lv_content.setOnRefreshListener(this);
        adapter = new PhotoListAdapter(getActivity());

        initNewBar();
        lv_content.getRefreshableView().addHeaderView(LayoutInflater.from(getActivity()).inflate(R.layout.title_photo_list, null));
        lv_content.setAdapter(adapter);
        lv_content.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (parent.getItemAtPosition(position) instanceof PhotoEntity) {
                    Intent intent = new Intent(getActivity(), PhotoInfoActivity.class);
                    intent.putExtra(PhotoInfoActivity.UUID, ((PhotoEntity) parent.getItemAtPosition(position)).getUuid());
                    getActivity().startActivity(intent);
                }
            }
        });

        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        onItemFirstShow();

    }

    void initNewBar() {
        posters = new ArrayList<>();
        topView = LayoutInflater.from(getActivity()).inflate(R.layout.photo_banner,null);
        v_n_top = (ConvenientBanner<PhotoEntity>) topView.findViewById(R.id.banner);
        v_n_top.setLayoutParams(new LinearLayout.LayoutParams(
                AbsListView.LayoutParams.MATCH_PARENT, (int) (ScreenUtil
                .getScreenWidth(getActivity()) / (16f / 9f))));
        v_n_top.setPageIndicator(new int[]{R.drawable.circle, R.drawable.circle_select});
        v_n_top.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
            @Override
            public NetworkImageHolderView createHolder() {
                return new NetworkImageHolderView();
            }
        }, posters);
        v_n_top.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Intent intent = new Intent(getActivity(), GameIndexActivity.class);
                PhotoEntity ob = posters.get(position);
                intent.putExtra(ArticleInfoActivity.UUID, ob.getUuid());
                getActivity().startActivity(intent);
            }
        });
        v_n_top.setShowtitle(false);
        lv_content.getRefreshableView().addHeaderView(topView);
    }

    void refreshBanner(List<PhotoEntity> posters) {
        if (posters == null) {
            posters = new ArrayList<>();
        }
        this.posters.clear();
        this.posters.addAll(posters);
        v_n_top.notifyDataSetChanged();
        if (this.posters.size() > 0) {
            topView.setVisibility(View.VISIBLE);
        } else {
            topView.setVisibility(View.GONE);
        }
    }

    private void refresh() {
        ResponseHandler handler = new ResponseHandler(TAG_REFRENSH);
        handler.setOnSucceedListener(this);
        handler.setOnFailedListener(this);
        PhotoMode.obtainPhotoList(handler, NewsMode.MODE_REFRESH);
    }

    private void loadmore() {
        ResponseHandler handler = new ResponseHandler(TAG_LOAD_MORE);
        handler.setOnSucceedListener(this);
        handler.setOnFailedListener(this);
        PhotoMode.obtainPhotoList(handler, NewsMode.MODE_LOAD_MORE);
    }

    @Override
    public void onFailed(String tag, ResponseHandler.FailedStatus status, int resultCode, String msg) {
        if (msg == null) {
            switch (status) {
                case DATA_ERROR:
                    ToastUtil.show(getActivity(), R.string.tip_data_error);
                    break;
                case NETWORK_ERROR:
                    ToastUtil.show(getActivity(), R.string.servererrortips);
                    break;
            }
        } else {
            ToastUtil.show(getActivity(), msg);
        }

        if (TAG_REFRENSH.equals(tag)) {
            if (loadView.getStatus() != LoadView.Status.successed) {
                loadView.setStatus(status == ResponseHandler.FailedStatus.DATA_ERROR ? LoadView.Status.data_error : LoadView.Status.network_error);
            }
            lv_content.onRefreshComplete();
        }
        if (TAG_LOAD_MORE.equals(tag)) {
            lv_content.onRefreshComplete();
        }
    }

    @Override
    public void onSucceed(String tag, boolean isCache, Object data) {
        if (TAG_REFRENSH.equals(tag)) {
            PhotoListEntity bean = (PhotoListEntity) data;
            refreshData(isCache, bean);
            refreshBanner(bean.getGames());
        }
        if (TAG_LOAD_MORE.equals(tag)) {
            PhotoListEntity beans = (PhotoListEntity) data;
            loadMoreData(beans.getExhibitions());
        }
    }

    /**
     * 刷新数据
     */
    private void refreshData(boolean isCache, PhotoListEntity beans) {
        if (!isCache) {
            if (beans == null || (beans.getExhibitions().size() == 0&&beans.getGames().size()==0)) {
                loadView.setStatus(LoadView.Status.not_data);
            } else {
                loadView.setStatus(LoadView.Status.successed);
                adapter.setPhotoEntities(beans.getExhibitions());
            }
            lv_content.getRefreshableView().setSelection(0);
        }
        saveLastUpdateTime();
        lv_content.onRefreshComplete();
    }


    /**
     * 保存最后更新时间
     */
    private void saveLastUpdateTime() {
        SharedPreferences.Editor lastUpdateTimeEditor = getActivity().getSharedPreferences(
                AppConstant.LastUpdateTimeKey.LAST_UPDATE_TIME.toString(),
                Context.MODE_PRIVATE).edit();
        lastUpdateTimeEditor.putLong(
                AppConstant.LastUpdateTimeKey.FINISHED_NEWS.toString(),
                System.currentTimeMillis()).commit();
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    /**
     * 加载更多
     */
    private void loadMoreData(List<PhotoEntity> beans) {
        if (beans == null || beans.size() == 0) {
            ToastUtil.show(getActivity(), R.string.no_more, Toast.LENGTH_SHORT);
        } else {
            adapter.addPhotoEntities(beans);
        }
        lv_content.onRefreshComplete();
    }


    @Override
    public void onRefreshTime(TextView view) {
        view.setText(TimeUtil.obtainLastUpdateTimeStatuString(getActivity(), getActivity()
                .getSharedPreferences(
                        AppConstant.LastUpdateTimeKey.LAST_UPDATE_TIME.toString(), 0)
                .getLong(AppConstant.LastUpdateTimeKey.FINISHED_NEWS.toString(), 0)));
    }

    public void onItemFirstShow() {
        PhotoListEntity bean = PhotoMode.getPhotoListByCache();
        if (bean != null) {
            List<PhotoEntity> matches = bean.getExhibitions();
            refreshBanner(bean.getGames());
            if (matches != null) {
                if (matches.size() > 0) {
                    loadView.setStatus(LoadView.Status.successed);
                } else {
                    loadView.setStatus(LoadView.Status.not_data);
                }
                adapter.setPhotoEntities(matches);
            }
            refresh();
        } else {
            loadView.setStatus(LoadView.Status.loading);
            refresh();
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        refresh();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        loadmore();
    }
}
